#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import uos as os
import micropython as mp
from machine import PWM, Timer, Pin


mp.alloc_emergency_exception_buf(1024)


class LedIsr(object):
    def __init__(self, timer, led):
        self.led = led
        timer.callback(self.cb)

    def cb(self, tim):
        self.toggle()
       # self.led.toggle()

    def toggle(self):
        self.led.toggle()


led = Pin(Pin.PB0, mode=Pin.MODE_OUT, value=1)
tim0 = Timer(0, mode=Timer.MODE_PRELOAD, unit=Timer.UNIT_MS, period=1000)
isr = LedIsr(tim0, led)
tim0.start()

pwm = PWM()
pwm.init(4, pwm.single, pwm.edgedwn, reload=True,
         psc=39, period=255, pwminv=False)
pwm.pwm_duty(4, 1)
pwm.pwm_start(4)


class Player(object):
    def __init__(self, filename, pwm_nr=4, timer_nr=5):
        print("do")
        # 8KHz=1ms触发8次, 即1000/8=125us/次
        self.timer = Timer(timer_nr, mode=Timer.MODE_PRELOAD, unit=Timer.UNIT_MS, period=1000)

        self.pwm_nr = pwm_nr
        self.pwm = PWM()

        self.handler = open(filename, "rb")   # file handler
        self.size = os.stat(filename)[6]      # file size
        print("hello")
        # 8KHz, buffer can play 2 second, buf1 and buf2 alternative used.
        self.buf = tuple(bytearray(8*1024), bytearray(8*1024))
        # 记录各个buf的有效字节数, 当两个buf都是0
        self.buf_len = [0, 0]

        self.which = 0  # self.buf[self.which]
        self.idx = 1    # idx = [0, 2*8*1000)

    #     # psc = 40000000/8000/(255+1)=19.53125, 40000000/16000/(255+1)=9.765625
    #     self.pwm.init(self.pwm_nr, self.pwm.single, self.pwm.edgedwn,
    #                   reload=True, psc=18, period=255, pwminv=False)
    #     self.init_player()

    # def init_player(self):
    #     self.which = 0
    #     self.idx = 1
    #     self.handler.seek(0, 0)                                      # 重置fp在开头
    #     self.buf_len[0] = self.handler.readinto(self.buf[0])         # 读8KB音频数据
    #     self.buf_len[1] = self.handler.readinto(self.buf[1])         # 读8KB音频数据
    #     self.pwm.duty(self.pwm_nr, self.buf[self.which][0])          # 设置首个PWM值

    # def is_finished(self):
    #     # 两个buffer长度为0, 文件到了末尾, 则播放完成
    #     if self.buf_len[0] <= 0 and self.buf_len[1] <= 0 and self.handler.ftell() >= self.size:
    #         return True
    #     else:
    #         return False

    # def resume_play(self):
    #     self.timer.start()
    #     self.pwm.start(self.pwm_nr)

    # def start_play(self):
    #     self.idx = 0
    #     self.resume_play(self)

    # def stop_play(self):
    #     self.timer.stop()
    #     self.pwm.stop(self.pwm_nr)

    # def callback(self, timer):
    #     if(self.idx >= self.buf_len[self.which]):
    #         self.idx = 0
    #         self.buf_len[self.which] = 0
    #         self.which = (self.which + 1) & 0x01
    #     else:
    #         self.pwm_duty(self.pwm_nr, self.buf[self.which][self.idx])
    #         self.idx += 1

    #     if self.is_finished():
    #         self.stop_play()
    #         print("play success")

  # read data?


if __name__ == "__main__":
    print("hello")
    player = Player("lib/pcmdata_8k.dat")
    pass
